<template>
  <div class="warpper">
    <div class="head">
      <el-row>
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="getDataPar.keyword" class="input-with-select">
            <el-button slot="append" @click="conditionSearch" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5" :offset="1">
          <span>时间：</span>
          <el-select v-model="timeSelectVal" placeholder="请选择" @change="timeSelectValChange">
            <el-option v-for="item in timeOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"> </el-option>
          </el-select>
        </el-col>
        <el-col :span="1">
          <el-button type="warning" icon="el-icon-refresh" @click="handleRef">重置</el-button>
        </el-col>
      </el-row>
      <div style="margin-bottom: 10px">
        <el-button icon="el-icon-plus" @click="handleAdd" type="primary">添加</el-button>
        <!-- <el-button icon="iconfont icon-daochu" @click="handleExport" type="success">导出</el-button> -->
        <el-button icon="el-icon-delete" @click="handleBatchDel" type="danger">批量删除</el-button>
      </div>
    </div>
    <div class="table">
      <el-table height="390px" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :data="tableData" :border="true" stripe style="width: 100%" tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="活动名称" min-width="150"> </el-table-column>
        <el-table-column prop="contacts" label="联系人" min-width="100">
          <template slot-scope="scoped">
            <el-tag>{{ scoped.row.contacts }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" min-width="150"> </el-table-column>
        <el-table-column prop="end_time" label="结束时间" min-width="150"> </el-table-column>
        <el-table-column prop="avatar" label="活动封面" min-width="220">
          <template slot-scope="scoped">
            <el-image :preview-src-list="srcList" @click="preview(scoped.row.avatar)" style="width: 200px; height: 120px; border-radius: 6px" :src="scoped.row.avatar" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="200"> </el-table-column>
        <el-table-column prop="address_desc" label="详细地址" min-width="200"> </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="150"> </el-table-column>
        <el-table-column prop="container" label="活动内容" min-width="150"> </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right">
          <template slot-scope="scoped">
            <el-button style="margin-right: 10px" icon="el-icon-delete" @click="handleDel(scoped.row)" type="danger">删除</el-button>
            <el-dropdown @command="handleCommand">
              <el-button type="primary"> 更多<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-edit" :command="{ data: scoped.row, flag: 'edit' }">编辑</el-dropdown-item>
                <el-dropdown-item icon="iconfont icon-baoming" :command="{ data: scoped.row, flag: 'signUp' }">报名</el-dropdown-item>
                <el-dropdown-item icon="iconfont icon-qiandao" :command="{ data: scoped.row, flag: 'signIn' }">签到</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="getDataPar.currentPage" :page-sizes="[15, 30, 50, 100]" :page-size="getDataPar.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>
    <!-- 添加或修改弹框 -->
    <el-dialog top="20px" :close-on-click-modal="false" :title="dialogTitle + '活动'" :visible.sync="dialogVisible" width="50%" @close="handleClose">
      <add-and-edit ref="bulletBox" @submit="submit" :ruleForm="editObj" @updateProps="updateProps"></add-and-edit>
    </el-dialog>

    <el-dialog top="20px" :title="dialogTitle + '详情' + '(' + gridData.length + '人)'" :visible.sync="upOrInDialogVisible" width="70%">
      <registrationOrCheckin :tableData="gridData"></registrationOrCheckin>
    </el-dialog>
  </div>
</template>

<script>
import { listPage, del, addOrEdit, batchDelete, exportActivity, inUpActivity } from '@/api/activityApi.js'
import addAndEdit from './AddAndEdit.vue'
import registrationOrCheckin from './RegistrationOrCheckin.vue'
export default {
  data() {
    return {
      loading: true,
      timeSelectVal: 0,
      dialogVisible: false, //添加和修改弹窗控制开关
      upOrInDialogVisible: false,
      editObj: {}, //修改行对象信息
      dialogTitle: '添加',
      options: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '女生',
        },
        {
          value: 2,
          label: '男生',
        },
      ],
      timeOptions: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '本周',
        },
        {
          value: 2,
          label: '本月',
        },
        {
          value: 3,
          label: '上半年',
        },
        {
          value: 4,
          label: '近一年',
        },
      ],
      tableData: [],
      selectTableRow: [],
      userInfo: {},
      getDataPar: {
        pageSize: 15,
        currentPage: 1,
        keyword: '',
        startTime: '',
        endTime: '',
      },
      total: 0,
      gridData: [],
      srcList: [],
    }
  },
  components: {
    addAndEdit,
    registrationOrCheckin,
  },
  created() {
    this.userInfo = this.userInfo = this.$sessionStorage('get', 'userInfo') ? this.$sessionStorage('get', 'userInfo') : {}
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      listPage(this.getDataPar).then((res) => {
        if (res.data.code != 200) return this.$message.error('数据请求失败')
        this.loading = false
        this.tableData = res.data.data.records
        this.tableData.forEach((item) => {
          item.startAndEndTime = [item.start_time, item.end_time]
          if (item.synopsis != null) {
            if (item.synopsis.length > 19) {
              item.container = item.synopsis.substring(0, 19) + '·····'
            }
          }
        })
        this.total = res.data.data.total
      })
    },
    handleSelectionChange(val) {
      this.selectTableRow = val
    },
    handleSizeChange(val) {
      this.getDataPar.pageSize = val
      this.getDataPar.currentPage = 1
      this.getData()
    },
    handleCurrentChange(val) {
      this.getDataPar.currentPage = val
      this.getData()
    },
    preview(url) {
      this.srcList = [url]
    },
    //关键字、性别、时间筛选
    conditionSearch() {
      this.getData()
    },
    timeSelectValChange(val) {
      // 获取当前时间
      const currentTime = this.$moment()

      let startOfYear = currentTime.startOf('year').format('YYYY-MM-DD HH:mm:ss')
      let endOffYear = currentTime.endOf('year').format('YYYY-MM-DD HH:mm:ss')
      switch (val) {
        case 0:
          this.getDataPar.startTime = ''
          this.getDataPar.endTime = ''
          break
        case 1: //本周
          let startOfWeek = this.$moment().startOf('week').format('YYYY-MM-DD HH:mm:ss')
          let endOfWeek = this.$moment().endOf('week').format('YYYY-MM-DD HH:mm:ss')
          this.getDataPar.startTime = startOfWeek
          this.getDataPar.endTime = endOfWeek
          break
        case 2: //本月
          let startOfMonth = this.$moment().startOf('month').format('YYYY-MM-DD HH:mm:ss')
          let endOfMonth = this.$moment().endOf('month').format('YYYY-MM-DD HH:mm:ss')
          this.getDataPar.startTime = startOfMonth
          this.getDataPar.endTime = endOfMonth
          break
        case 3: //上半年
          let startOfHalfYear = currentTime.startOf('year').add(6, 'months').format('YYYY-MM-DD HH:mm:ss')
          this.getDataPar.startTime = startOfHalfYear
          this.getDataPar.endTime = endOffYear
          break
        case 4: //今年
          this.getDataPar.startTime = startOfYear
          this.getDataPar.endTime = endOffYear
          break
      }
      this.getData()
    },
    //重置条件筛选
    handleRef() {
      this.getDataPar = {
        pageSize: 15,
        currentPage: 1,
        keyword: '',
        startTime: '',
        endTime: '',
      }
      this.timeSelectVal = 0
      this.getData()
    },
    //添加
    handleAdd() {
      this.dialogTitle = '添加'
      this.dialogVisible = true
      this.editObj = {
        avatar: '',
      }
    },
    handleCommand(obj) {
      switch (obj.flag) {
        case 'edit':
          this.dialogTitle = '修改'
          this.dialogVisible = true
          this.editObj = JSON.parse(JSON.stringify(obj.data))
          break
        case 'signUp':
          this.dialogTitle = '报名'
          this.upOrInDialogVisible = true
          this.getInUpActivity(obj.data.id, 2)
          break
        case 'signIn':
          this.dialogTitle = '签到'
          this.upOrInDialogVisible = true
          this.getInUpActivity(obj.data.id, 3)
          break
      }
    },
    //获取签到用户或报名用户
    getInUpActivity(id, type) {
      inUpActivity({ id, type }).then((res) => {
        this.gridData = res.data.data
      })
    },
    //导出
    handleExport() {
      exportActivity().then((res) => {
        console.log(res)
      })
    },
    //删除
    handleDel(row) {
      this.$confirm(`确定删除${row.name}活动吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          del({ id: row.id }).then((res) => {
            if (res.data.code != 200) return this.$message.error(`删除${row.name}失败！！！`)
            this.$message.success(`用户 ${row.name} 删除成功!`)
            this.getData()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    //批量删除
    handleBatchDel() {
      this.$confirm(`确定此操作吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let idList = []
          let tips = ''

          if (this.selectTableRow.length == 0) {
            return this.$message.warning(`请选择要删除的项`)
          }
          this.selectTableRow.forEach((item, i) => {
            idList.push(item.id)
            if (i == this.selectTableRow.length - 1) {
              tips += item.name
            } else {
              tips += item.name + ','
            }
          })
          batchDelete(idList).then((res) => {
            if (res.data.code != 200) return this.$message.error(`批量删除失败！！！`)
            this.$message.success(`${tips} 活动已被删除`)
            this.getData()
          })
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    },
    //提交表单，添加或编辑
    submit(formData) {
      this.dialogVisible = false
      addOrEdit(formData).then((res) => {
        if (res.data.code != 200) return this.$message.error(`${this.dialogTitle}失败！！！`)
        this.$message.success(`${this.dialogTitle}成功`)
        this.getData()
        //如果修改的是当前登录的管理员则更新存储信息
        if (formData.id && formData.id == this.userInfo.id) {
          this.$emit('upUserInfo', formData.id)
        }
      })
    },
    //更新子组件props
    updateProps(newProps) {
      this.editObj = newProps
    },
    //关闭弹框
    handleClose() {
      this.$refs.bulletBox.resetForm()
    },
  },
}
</script>

<style lang="less" scoped>
.block {
  margin-top: 15px;
}
</style>